import {
  login,
  logout,
  getUserInfo,
  getMessage,
  getContentByMsgId,
  hasRead,
  removeReaded,
  restoreTrash,
  getUnreadCount,
  getUserSysMenu
} from '@/api/user'
import { menuRefactoring } from '@/libs/business_util'
import { getRouterReq } from '@/api/routers'
import { setToken, setRefreshToken, getToken, getRefreshToken, setRole, getRole,routersConfigAssembly} from '@/libs/util'
import _ from 'lodash'

export default {
  state: {
    userName: '',
    userId: '',
    avatorImgPath: '',
    token: getToken(),
    refreshToken: getRefreshToken(),
    role: getRole(),
    access: '',
    hasGetInfo: false,
    unreadCount: 0,
    messageUnreadList: [],
    messageReadedList: [],
    messageTrashList: [],
    messageContentStore: {}
  },
  mutations: {
    setAvator (state, avatorPath) {
      state.avatorImgPath = avatorPath
    },
    setUserId (state, id) {
      state.userId = id
    },
    setUserName (state, name) {
      state.userName = name
    },
    setAccess (state, access) {
      state.access = access
    },
    setToken (state, token) {
      state.token = token
      setToken(token)
    },
    setRefreshToken (state, token) {
      state.refreshToken = token
      setRefreshToken(token)
    },
    setRole (state, role) {
      state.role = role
      setRole(role)
    },
    setHasGetInfo (state, status) {
      state.hasGetInfo = status
    },
    setMessageCount (state, count) {
      state.unreadCount = count
    },
    setMessageUnreadList (state, list) {
      state.messageUnreadList = list
    },
    setMessageReadedList (state, list) {
      state.messageReadedList = list
    },
    setMessageTrashList (state, list) {
      state.messageTrashList = list
    },
    updateMessageContentStore (state, { msg_id, content }) {
      state.messageContentStore[msg_id] = content
    },
    moveMsg (state, { from, to, msg_id }) {
      const index = state[from].findIndex(_ => _.msg_id === msg_id)
      const msgItem = state[from].splice(index, 1)[0]
      msgItem.loading = false
      state[to].unshift(msgItem)
    }
  },
  getters: {
    messageUnreadCount: state => state.messageUnreadList.length,
    messageReadedCount: state => state.messageReadedList.length,
    messageTrashCount: state => state.messageTrashList.length
  },
  actions: {
    // 登录
    handleLogin ({ commit }, {userName, password}) {
      userName = userName.trim()
      return new Promise((resolve, reject) => {
        login({
          userName,
          password
        }).then(res => {
          const data = res.data
          if(data.code === 200){
            commit('setUserName', data.data.name)
            commit('setToken', data.data.accessToken)
            commit('setRefreshToken', data.data.refreshToken)
            commit('setRole', data.data.role)
            commit('setAccess', data.data.role)
          }
          resolve(data)
        }).catch(err => {
          reject(err)
        })
      })
    },
    // 退出登录
    handleLogOut ({ state, commit }) {
      return new Promise((resolve, reject) => {
        logout(state.token).then(() => {
          commit('setUserName', '')
          commit('setToken', '')
          commit('setAccess', [])
          resolve()
        }).catch(err => {
          commit('setUserName', '')
          commit('setToken', '')
          commit('setAccess', [])
          resolve()
          reject(err)
        })
        // 如果你的退出登录无需请求接口，则可以直接使用下面三行代码而无需使用logout调用接口
        // commit('setToken', '')
        // commit('setAccess', [])
        // resolve()
      })
    },
    // 获取用户路由
    getRoutersConfig ({ state, commit }) {
      /* 有标准路由JOSN模式
       return getRouterReq().then((routersData) => {
       let routersConfig = _.cloneDeep(routersData.data)
       let newRoutersConfigObj = routersConfigAssembly(routersConfig)
       commit('setRoutersConfig', { newRouters: newRoutersConfigObj, routersData: routersData.data })
       return newRoutersConfigObj
       })*/
      //  console.log('获取到用户菜单：' + JSON.stringify(routersData.data))
      // 把菜单列表转为框架标准路由JSON格式
      /*需要转换菜单JOSN为标准路由JOSN模式*/
      return getUserSysMenu().then((routersData) => {
        // let routersData=[{'id': '1', 'parent_id': '0', 'menu_title': '系统管理', 'menu_name': 'system', 'menu_cache': 1, 'menu_hide': 0, 'menu_icon': 'logo-buffer', 'menu_type': 3, 'menu_href': '', 'menu_component': ''},
        //   {'id': '2', 'parent_id': '1', 'menu_title': '子系统管理', 'menu_name': 'subsystem', 'menu_cache': 1, 'menu_hide': 0, 'menu_icon': 'md-trending-up', 'menu_type': 3, 'menu_href': '', 'menu_component': 'CountTo'},
        //   {'id': '3', 'parent_id': '1', 'menu_title': '菜单管理', 'menu_name': 'menu', 'menu_cache': 1, 'menu_hide': 0, 'menu_icon': 'ios-infinite', 'menu_type': 3, 'menu_href': '', 'menu_component': 'DragList'}
        //   /*      {"id":"4","parent_id":"3","menu_title":"菜单信息管理","menu_name":"menu_list","menu_cache":1,"menu_icon":"ios-infinite","menu_type":3,"menu_href":"components/drag-list/drag-list.vue"},
        //    {"id":"5","parent_id":"3","menu_title":"菜单权限管理","menu_name":"role_list","menu_cache":1,"menu_icon":"ios-infinite","menu_type":3,"menu_href":"components/tables/tables.vue"} */
        // ]
        if(routersData.data.code !=200){
              return
        }
        let newRoutersData = menuRefactoring(routersData.data.data, '0')

        //  console.log("转换路由："+JSON.stringify(newRoutersData))
        let routersConfig = _.cloneDeep(newRoutersData)
        let newRoutersConfigObj = routersConfigAssembly(routersConfig)
        commit('setRoutersConfig', { newRouters: newRoutersConfigObj, routersData: newRoutersData })
        return newRoutersConfigObj
      })

      /*需要转换菜单JOSN为标准路由JOSN模式*/
      // return getUserSysMenu().then((routersData) => {
      //
      // })
    }
    // 获取用户相关信息
    // getUserInfo ({ state, commit }) {
    //   return new Promise((resolve, reject) => {
    //     try {
    //       getUserInfo(state.token).then(res => {
    //         const data = res.data
    //         commit('setAvator', data.avator)
    //         commit('setUserName', data.name)
    //         commit('setUserId', data.user_id)
    //         commit('setAccess', data.access)
    //         commit('setHasGetInfo', true)
    //         resolve(data)
    //       }).catch(err => {
    //         reject(err)
    //       })
    //     } catch (error) {
    //       reject(error)
    //     }
    //   })
    // },
    // // 此方法用来获取未读消息条数，接口只返回数值，不返回消息列表
    // getUnreadMessageCount ({ state, commit }) {
    //   getUnreadCount().then(res => {
    //     const { data } = res
    //     commit('setMessageCount', data)
    //   })
    // },
    // // 获取消息列表，其中包含未读、已读、回收站三个列表
    // getMessageList ({ state, commit }) {
    //   return new Promise((resolve, reject) => {
    //     getMessage().then(res => {
    //       const { unread, readed, trash } = res.data
    //       commit('setMessageUnreadList', unread.sort((a, b) => new Date(b.create_time) - new Date(a.create_time)))
    //       commit('setMessageReadedList', readed.map(_ => {
    //         _.loading = false
    //         return _
    //       }).sort((a, b) => new Date(b.create_time) - new Date(a.create_time)))
    //       commit('setMessageTrashList', trash.map(_ => {
    //         _.loading = false
    //         return _
    //       }).sort((a, b) => new Date(b.create_time) - new Date(a.create_time)))
    //       resolve()
    //     }).catch(error => {
    //       reject(error)
    //     })
    //   })
    // },
    // // 根据当前点击的消息的id获取内容
    // getContentByMsgId ({ state, commit }, { msg_id }) {
    //   return new Promise((resolve, reject) => {
    //     let contentItem = state.messageContentStore[msg_id]
    //     if (contentItem) {
    //       resolve(contentItem)
    //     } else {
    //       getContentByMsgId(msg_id).then(res => {
    //         const content = res.data
    //         commit('updateMessageContentStore', { msg_id, content })
    //         resolve(content)
    //       })
    //     }
    //   })
    // },
    // // 把一个未读消息标记为已读
    // hasRead ({ state, commit }, { msg_id }) {
    //   return new Promise((resolve, reject) => {
    //     hasRead(msg_id).then(() => {
    //       commit('moveMsg', {
    //         from: 'messageUnreadList',
    //         to: 'messageReadedList',
    //         msg_id
    //       })
    //       commit('setMessageCount', state.unreadCount - 1)
    //       resolve()
    //     }).catch(error => {
    //       reject(error)
    //     })
    //   })
    // },
    // // 删除一个已读消息到回收站
    // removeReaded ({ commit }, { msg_id }) {
    //   return new Promise((resolve, reject) => {
    //     removeReaded(msg_id).then(() => {
    //       commit('moveMsg', {
    //         from: 'messageReadedList',
    //         to: 'messageTrashList',
    //         msg_id
    //       })
    //       resolve()
    //     }).catch(error => {
    //       reject(error)
    //     })
    //   })
    // },
    // // 还原一个已删除消息到已读消息
    // restoreTrash ({ commit }, { msg_id }) {
    //   return new Promise((resolve, reject) => {
    //     restoreTrash(msg_id).then(() => {
    //       commit('moveMsg', {
    //         from: 'messageTrashList',
    //         to: 'messageReadedList',
    //         msg_id
    //       })
    //       resolve()
    //     }).catch(error => {
    //       reject(error)
    //     })
    //   })
    // }
  }
}
